package top.braycep.ui;

import top.braycep.task.CheckUpdateTask;
import top.braycep.task.DownloadTask;
import top.braycep.utils.AppUtils;
import top.braycep.utils.FileUtils;
import top.braycep.utils.TreeUtils;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Enumeration;
import java.util.logging.Logger;
/*
 * Created by JFormDesigner on Tue Feb 15 09:47:33 CST 2022
 */


/**
 * @author 123
 */
public class MainUI extends JFrame {
    private static final Logger logger = Logger.getLogger(MainUI.class.getName());

    private JMenuItem menuDownload;

    public MainUI() {
        initComponents();

        initCustomLayout();

        initCustomEvents();
    }

    public void initCustomLayout() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 初始化编辑界面文件路径选择
        tableFiles.getColumnModel().getColumn(2).setCellRenderer(new ButtonRender());
        tableFiles.getColumnModel().getColumn(2).setCellEditor(new ButtonEditor(this));

        // 添加点击事件
        JPopupMenu popupMenuList = new JPopupMenu();
        JMenuItem menuItemLoad = new JMenuItem("加载");
        JMenuItem menuItemCreate = new JMenuItem("生成");
        JMenuItem menuItemDefault = new JMenuItem("默认");
        JMenuItem menuItemDelete = new JMenuItem("删除");
        menuItemDelete.setForeground(Color.red);
        popupMenuList.add(menuItemLoad);
        popupMenuList.add(menuItemCreate);
        popupMenuList.add(menuItemDefault);
        popupMenuList.addSeparator();
        popupMenuList.add(menuItemDelete);
        tableList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.getButton() == 3 && e.getClickCount() == 1) {
                    popupMenuList.show(tableList, e.getX(), e.getY());
                }
            }
        });

        menuItemLoad.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {

            }
        });

        menuItemCreate.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                AppUtils.showInfo(MainUI.this, "提示", "生成成功");
            }
        });

        menuItemDefault.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {

            }
        });

        menuItemDelete.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {

            }
        });

        // table files

        // menu about
        menuDownload = new JMenuItem("下载新版");
        menuDownload.setForeground(Color.red);
        menuDownload.setVisible(false);
        menuDownload.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                new DownloadTask(MainUI.this).execute();
            }
        });
        menuAbout.add(menuDownload);
    }

    public void initCustomEvents() {
        menuItemAbout.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                JDialog dialogMsgBox = AboutUI.getDialogMsgBox();
                dialogMsgBox.setLocationRelativeTo(MainUI.this);
                dialogMsgBox.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                dialogMsgBox.show();
            }
        });

        buttonChooseSaveFolder.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                File file = FileUtils.chooseDir(MainUI.this, null);
                if (file != null) {
                    textFieldSavePath.setText(file.getAbsolutePath());
                }
            }
        });

        menuItemCheckUpdate.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
//                Version version = UpdateUtils.checkUpdate();
//                boolean hasNew = version.getVersion() > 0;
//                AboutUI.hasNew = hasNew;
//                if (!hasNew) {
//                    menuDownload.setVisible(false);
//                    AppUtils.showInfo(MainUI.this, "提示", "已经是最新版本");
//                } else {
//                    newVersion = version;
//                    menuDownload.setVisible(true);
//                    AppUtils.showInfo(MainUI.this, "提示", "发现新版本：v" + version.getVersion());
//                }

                new CheckUpdateTask(MainUI.this, menuDownload).execute();
            }
        });

        menuItemPreview.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                previewTree();
            }
        });

        treePreview.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.getButton() == 3 && e.getClickCount() == 1) {
                    JPopupMenu popupMenu = new JPopupMenu();
                    JMenuItem menuItemRefresh = new JMenuItem("刷新");
                    JMenuItem menuItemExpand = new JMenuItem("展开");
                    menuItemExpand.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseReleased(MouseEvent e) {
                            expandTree(true);
                        }
                    });
                    JMenuItem menuItemFold = new JMenuItem("折叠");
                    menuItemFold.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseReleased(MouseEvent e) {
                            expandTree(false);
                        }
                    });
                    menuItemRefresh.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseReleased(MouseEvent e) {
                            previewTree();
                        }
                    });
                    popupMenu.add(menuItemRefresh);
                    popupMenu.addSeparator();
                    popupMenu.add(menuItemExpand);
                    popupMenu.add(menuItemFold);
                    popupMenu.show(treePreview, e.getX(), e.getY());
                }
            }
        });
    }

    public void expandTree(boolean isExpand) {
        DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) treePreview.getModel().getRoot();
        doExpand(new TreePath(rootNode), isExpand);
    }

    public void doExpand(TreePath path, boolean isExpand) {
        TreeNode node = (TreeNode) path.getLastPathComponent();
        if (node.getChildCount() >= 0) {
            Enumeration children = node.children();
            while (children.hasMoreElements()) {
                TreeNode child = (TreeNode) children.nextElement();
                doExpand(path.pathByAddingChild(child), isExpand);
            }
        }

        if (isExpand) {
            treePreview.expandPath(path);
        } else {
            treePreview.collapsePath(path);
        }
    }

    public void previewTree() {
        TreeUtils.preview(treePreview, textFieldFileName.getText(), (DefaultTableModel) tableFiles.getModel());
        treePreview.updateUI();
        if (!treePreview.isShowing()) {
            tabbedPane.setSelectedIndex(2);
        }
    }

    public JCheckBoxMenuItem getCheckBoxMenuItemAnalysisPath() {
        return checkBoxMenuItemAnalysisPath;
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        menuBar = new JMenuBar();
        menuFile = new JMenu();
        menuItemChooseDB = new JMenuItem();
        menuItemExit = new JMenuItem();
        menuTool = new JMenu();
        checkBoxMenuItemAnalysisPath = new JCheckBoxMenuItem();
        menuItemPreview = new JMenuItem();
        menuAbout = new JMenu();
        menuItemCheckUpdate = new JMenuItem();
        menuItemAbout = new JMenuItem();
        tabbedPane = new JTabbedPane();
        scrollPaneList = new JScrollPane();
        tableList = new JTable();
        panelEdit = new JPanel();
        panelTool = new JPanel();
        buttonNew = new JButton();
        buttonSave = new JButton();
        buttonCreateJar = new JButton();
        buttonReload = new JButton();
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();
        textFieldFileName = new JTextField();
        panel4 = new JPanel();
        textFieldSavePath = new JTextField();
        buttonChooseSaveFolder = new JButton();
        scrollPane1 = new JScrollPane();
        tableFiles = new JTable();
        panel5 = new JPanel();
        scrollPane2 = new JScrollPane();
        treePreview = new JTree();

        //======== this ========
        setTitle("JarBuilder");
        setMinimumSize(new Dimension(800, 600));
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        //======== menuBar ========
        {

            //======== menuFile ========
            {
                menuFile.setText("\u6587\u4ef6");

                //---- menuItemChooseDB ----
                menuItemChooseDB.setText("\u6253\u5f00");
                menuFile.add(menuItemChooseDB);
                menuFile.addSeparator();

                //---- menuItemExit ----
                menuItemExit.setText("\u9000\u51fa");
                menuFile.add(menuItemExit);
            }
            menuBar.add(menuFile);

            //======== menuTool ========
            {
                menuTool.setText("\u5de5\u5177");

                //---- checkBoxMenuItemAnalysisPath ----
                checkBoxMenuItemAnalysisPath.setText("\u8bc6\u522b\u8def\u5f84");
                checkBoxMenuItemAnalysisPath.setToolTipText("\u81ea\u52a8\u8bc6\u522b\u6240\u9009Class\u6587\u4ef6\u8def\u5f84\uff0c\u5e76\u586b\u5145\u5305\u540d");
                menuTool.add(checkBoxMenuItemAnalysisPath);

                //---- menuItemPreview ----
                menuItemPreview.setText("\u9884\u89c8");
                menuTool.add(menuItemPreview);
            }
            menuBar.add(menuTool);

            //======== menuAbout ========
            {
                menuAbout.setText("\u5e2e\u52a9");

                //---- menuItemCheckUpdate ----
                menuItemCheckUpdate.setText("\u68C0\u67E5\u66f4\u65b0");
                menuAbout.add(menuItemCheckUpdate);

                //---- menuItemAbout ----
                menuItemAbout.setText("\u5173\u4e8e");
                menuAbout.add(menuItemAbout);
            }
            menuBar.add(menuAbout);
        }
        setJMenuBar(menuBar);

        //======== tabbedPane ========
        {

            //======== scrollPaneList ========
            {

                //---- tableList ----
                tableList.setModel(new DefaultTableModel(
                        new Object[][]{
                                {123, null, null, true, null},
                        },
                        new String[]{
                                "I", "\u6587\u4ef6\u540d", "\u4fdd\u5b58\u8def\u5f84", "\u9ed8\u8ba4", "\u5907\u6ce8"
                        }
                ) {
                    Class<?>[] columnTypes = new Class<?>[]{
                            Integer.class, String.class, String.class, Boolean.class, String.class
                    };
                    boolean[] columnEditable = new boolean[]{
                            false, false, false, false, false
                    };

                    @Override
                    public Class<?> getColumnClass(int columnIndex) {
                        return columnTypes[columnIndex];
                    }

                    @Override
                    public boolean isCellEditable(int rowIndex, int columnIndex) {
                        return columnEditable[columnIndex];
                    }
                });
                {
                    TableColumnModel cm = tableList.getColumnModel();
                    cm.getColumn(0).setResizable(false);
                    cm.getColumn(0).setMaxWidth(50);
                    cm.getColumn(0).setPreferredWidth(30);
                    cm.getColumn(3).setMaxWidth(50);
                    cm.getColumn(3).setPreferredWidth(50);
                }
                tableList.setBorder(new LineBorder(Color.lightGray));
                tableList.setCellSelectionEnabled(true);
                tableList.setFillsViewportHeight(true);
                tableList.setRowHeight(20);
                scrollPaneList.setViewportView(tableList);
            }
            tabbedPane.addTab("\u5217\u8868", scrollPaneList);

            //======== panelEdit ========
            {
                panelEdit.setLayout(new BorderLayout());

                //======== panelTool ========
                {
                    panelTool.setMaximumSize(new Dimension(32767, 33));
                    panelTool.setBorder(new LineBorder(Color.lightGray));
                    panelTool.setLayout(new FlowLayout(FlowLayout.LEFT));

                    //---- buttonNew ----
                    buttonNew.setText("\u65b0\u589e");
                    panelTool.add(buttonNew);

                    //---- buttonSave ----
                    buttonSave.setText("\u4fdd\u5b58");
                    panelTool.add(buttonSave);

                    //---- buttonCreateJar ----
                    buttonCreateJar.setText("\u751f\u6210");
                    panelTool.add(buttonCreateJar);

                    //---- buttonReload ----
                    buttonReload.setText("\u91cd\u8f7d");
                    panelTool.add(buttonReload);
                }
                panelEdit.add(panelTool, BorderLayout.NORTH);

                //======== panel1 ========
                {
                    panel1.setLayout(new BorderLayout());

                    //======== panel2 ========
                    {
                        panel2.setLayout(new GridLayout(1, 2));

                        //======== panel3 ========
                        {
                            panel3.setBorder(new TitledBorder(null, "*Jar\u6587\u4ef6\u540d", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, null, Color.red));
                            panel3.setLayout(new BorderLayout());

                            //---- textFieldFileName ----
                            textFieldFileName.setBackground(Color.white);
                            panel3.add(textFieldFileName, BorderLayout.CENTER);
                        }
                        panel2.add(panel3);

                        //======== panel4 ========
                        {
                            panel4.setBorder(new TitledBorder(null, "*Jar\u4fdd\u5b58\u8def\u5f84", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, null, Color.red));
                            panel4.setLayout(new BorderLayout());
                            panel4.add(textFieldSavePath, BorderLayout.CENTER);

                            //---- buttonChooseSaveFolder ----
                            buttonChooseSaveFolder.setText("\u9009\u62e9");
                            buttonChooseSaveFolder.setIcon(UIManager.getIcon("FileView.directoryIcon"));
                            panel4.add(buttonChooseSaveFolder, BorderLayout.EAST);
                        }
                        panel2.add(panel4);
                    }
                    panel1.add(panel2, BorderLayout.NORTH);

                    //======== scrollPane1 ========
                    {

                        //---- tableFiles ----
                        tableFiles.setModel(new DefaultTableModel(
                                new Object[][]{
                                        {null, null, "...", null, null, null, true, null},
                                },
                                new String[]{
                                        "I", "\u6587\u4ef6\u8def\u5f84", " ", "\u6620\u5c04\u8def\u5f84", "\u6b63\u5219\u5bfc\u5165", "\u6b63\u5219\u6392\u9664", "\u542f\u7528", "\u5907\u6ce8"
                                }
                        ) {
                            Class<?>[] columnTypes = new Class<?>[]{
                                    Integer.class, Object.class, Object.class, String.class, String.class, String.class, Boolean.class, String.class
                            };
                            boolean[] columnEditable = new boolean[]{
                                    false, true, true, true, true, true, true, true
                            };

                            @Override
                            public Class<?> getColumnClass(int columnIndex) {
                                return columnTypes[columnIndex];
                            }

                            @Override
                            public boolean isCellEditable(int rowIndex, int columnIndex) {
                                return columnEditable[columnIndex];
                            }
                        });
                        {
                            TableColumnModel cm = tableFiles.getColumnModel();
                            cm.getColumn(0).setResizable(false);
                            cm.getColumn(0).setMaxWidth(40);
                            cm.getColumn(0).setPreferredWidth(40);
                            cm.getColumn(2).setResizable(false);
                            cm.getColumn(2).setMinWidth(20);
                            cm.getColumn(2).setMaxWidth(20);
                            cm.getColumn(2).setPreferredWidth(20);
                            cm.getColumn(6).setResizable(false);
                            cm.getColumn(6).setMaxWidth(50);
                            cm.getColumn(6).setPreferredWidth(50);
                        }
                        tableFiles.setBorder(new LineBorder(Color.lightGray));
                        tableFiles.setCellSelectionEnabled(true);
                        tableFiles.setFillsViewportHeight(true);
                        tableFiles.setRowHeight(20);
                        scrollPane1.setViewportView(tableFiles);
                    }
                    panel1.add(scrollPane1, BorderLayout.CENTER);
                }
                panelEdit.add(panel1, BorderLayout.CENTER);
            }
            tabbedPane.addTab("\u7f16\u8f91", panelEdit);

            //======== panel5 ========
            {
                panel5.setLayout(new BorderLayout());

                //======== scrollPane2 ========
                {

                    //---- treePreview ----
                    treePreview.setModel(new DefaultTreeModel(
                            new DefaultMutableTreeNode("JarFile") {
                                {
                                    add(new DefaultMutableTreeNode("file1"));
                                    DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("file2");
                                    node1.add(new DefaultMutableTreeNode("file3"));
                                    add(node1);
                                }
                            }));
                    treePreview.setFont(new Font("\u5b8b\u4f53", Font.PLAIN, 14));
                    scrollPane2.setViewportView(treePreview);
                }
                panel5.add(scrollPane2, BorderLayout.CENTER);
            }
            tabbedPane.addTab("\u9884\u89c8", panel5);
        }
        contentPane.add(tabbedPane, BorderLayout.CENTER);
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JMenuBar menuBar;
    private JMenu menuFile;
    private JMenuItem menuItemChooseDB;
    private JMenuItem menuItemExit;
    private JMenu menuTool;
    private JCheckBoxMenuItem checkBoxMenuItemAnalysisPath;
    private JMenuItem menuItemPreview;
    private JMenu menuAbout;
    private JMenuItem menuItemCheckUpdate;
    private JMenuItem menuItemAbout;
    private JTabbedPane tabbedPane;
    private JScrollPane scrollPaneList;
    private JTable tableList;
    private JPanel panelEdit;
    private JPanel panelTool;
    private JButton buttonNew;
    private JButton buttonSave;
    private JButton buttonCreateJar;
    private JButton buttonReload;
    private JPanel panel1;
    private JPanel panel2;
    private JPanel panel3;
    private JTextField textFieldFileName;
    private JPanel panel4;
    private JTextField textFieldSavePath;
    private JButton buttonChooseSaveFolder;
    private JScrollPane scrollPane1;
    private JTable tableFiles;
    private JPanel panel5;
    private JScrollPane scrollPane2;
    private JTree treePreview;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}
